class Circle {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.r = Math.random() * 5 + 5;
        this._mx = Math.random() + 1 - (this.r / 10);
        this._my = Math.random() + 1 - (this.r / 10);
    }

    drawCircle(ctx) {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.r, 0, 360)
        ctx.closePath();
        ctx.fillStyle = 'rgba(204, 204, 204, 0.7)';
        ctx.fill();
    }

    drawLine(ctx, _circle) {
        let dx = this.x - _circle.x;
        let dy = this.y - _circle.y;
        let d = Math.sqrt(dx * dx + dy * dy)
        if (d < 150) {
            let opacity = 1 - (d / 150);

            ctx.beginPath();
            ctx.moveTo(this.x, this.y);
            ctx.lineTo(_circle.x, _circle.y);
            ctx.closePath();
            ctx.strokeStyle = 'rgba(204, 204, 204, ' + opacity + ')';
            ctx.stroke();
        }
    }

    move(w, h){
        this._mx = (this.x < w && this.x > 0) ? this._mx : -this._mx;
        this._my = (this.y < h && this.y > 0) ? this._my : -this._my;
        this.x += this._mx;
        this.y += this._my;
    }

    moveCrash(ctx, _circle){
        let dx = this.x - _circle.x;
        let dy = this.y - _circle.y;
        let d = Math.sqrt(dx * dx + dy * dy);

        if( d < this.r + _circle.r + Math.abs(this._mx) + Math.abs(this._my) ){
            this._mx = -this._mx;
            this._my = -this._my;
            _circle._mx = _circle._mx;
            _circle._my = -_circle._my;
        }
    }
}

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

let frameDom = document.getElementsByClassName('content')[0].getElementsByTagName('span')[0];

let w = canvas.width = canvas.offsetWidth;
let h = canvas.height = canvas.offsetHeight;
let circles = [];

let frame = 0;

function draw(){
    ctx.clearRect(0, 0, w, h);
    for( let i = 0; i < circles.length; i++ ){
        circles[i].move(w, h);
        circles[i].drawCircle(ctx);
        
        for(let j = i + 1; j < circles.length; j++){
            circles[i].drawLine(ctx, circles[j]);
            circles[i].moveCrash(ctx, circles[j]);
        }
    }

    frame++;

    requestAnimationFrame(draw);
}

function init(num){
    for(var i = 0; i < num; i++){
        circles.push(new Circle(Math.random() * w, Math.random() * h));
    }

    setInterval(function(){
        frameDom.innerHTML = frame;
        frame = 0;
    }, 1000)

    draw();
}

init(200);